package com.atguigu.tingshu.order.template;

import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OrderConfirmClient implements ApplicationContextAware {

    private static final Map<String, OrderConfirmTemplate> MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(TemplateBean.class);
        if (CollectionUtils.isNotEmpty(beanMap)){
            Collection<Object> beans = beanMap.values();
            beans.forEach(bean -> {
                TemplateBean templateBean = bean.getClass().getAnnotation(TemplateBean.class);
                MAP.put(templateBean.type(), (OrderConfirmTemplate) bean);
            });
        }
    }

    public OrderInfoVo confirm(TradeVo tradeVo){
        return MAP.get(tradeVo.getItemType()).confirm(tradeVo);
    }
}
